<template>
  <div class="settled-wrapper wrapper_1200">
    <div class="user-com-title">
      入驻申请
    </div>
    <div class="settled-main">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm"
               @submit.native.prevent>
        <el-form-item label="商户名称：" prop="name">
          <el-input v-model="ruleForm.name" placeholder="请输入商户名称"></el-input>
        </el-form-item>
        <el-form-item label="用户姓名：" prop="username">
          <el-input v-model="ruleForm.username" placeholder="请输入用户姓名"></el-input>
        </el-form-item>
        <el-form-item label="手机号：" prop="phone">
          <el-input v-model="ruleForm.phone" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item label="验证码：" prop="yanzhengma">
          <el-input v-model="ruleForm.yanzhengma" placeholder="请输入验证码" class="verifiCode"></el-input>
          <button class="code font-color" :disabled="disabled" :class="disabled === true ? 'on' : ''" @click="getVerify">
            {{ text }}
          </button>
        </el-form-item>
        <el-form-item label="图片验证码：" v-if="isShowCode">
          <el-input v-model="codeVal" placeholder="请输入验证码" class="verifiCode"></el-input>
          <span class="imageCode" @click="again"><img :src="codeUrl" alt=""></span>
        </el-form-item>
        <el-form-item label="商户分类：" prop="classification">
          <el-select v-model="ruleForm.classification" placeholder="请选择商户分类">
            <el-option
              :label="item.category_name"
              :value="item.merchant_category_id"
              v-for="(item, index) in array"
              :key="index"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="店铺类型：" prop="type">
          <el-select v-model="ruleForm.type" placeholder="请选择店铺类型">
            <el-option
              :label="item.type_name"
              :value="item.mer_type_id"
              v-for="(item, index) in typeArray"
              :key="index"
            ></el-option>
          </el-select>
          <span class="iconfont wenhao" @click="getStoreType">?</span>
        </el-form-item>
        <el-form-item label="营业执照：">
          <div class="text">
            请上传营业执照及行业相关资质证明图片
            <span class="text-desc">(图片最多可上传10张， 单张图片不超过2M， 图片格式支持JPG、PNG、JPEG)</span>
          </div>
          <div class="imageUrl">
            <!-- <ul class="imgCont">
                <li class="imgList" v-for="(item,index) in imgUrl" :key="index">
                    <img width="100%" :src="item" alt="">
                </li>
            </ul> -->
            <!-- 图片回填 -->
            <ul v-for="(item,index) in imgUrl" :key="index" class="el-upload-list el-upload-list--picture-card">
              <li tabindex="0" class="el-upload-list__item is-success">
                <img :src="item" alt="" class="el-upload-list__item-thumbnail">
                <a class="el-upload-list__item-name"><i class="el-icon-document"></i></a>
                <label class="el-upload-list__item-status-label"><i
                  class="el-icon-upload-success el-icon-check"></i></label>
                <i class="el-icon-close"></i><i class="el-icon-close-tip">按 delete 键可删除</i><span
                class="el-upload-list__item-actions">
                                <span class="el-upload-list__item-delete" @click="handleRemove1(index)"><i
                                  class="el-icon-delete"></i></span></span>
              </li>
            </ul>
          </div>
          <el-upload
            :action="upLoadUrl"
            list-type="picture-card"
            :limit="currentLimit"
            accept="image/*"
            :before-upload="beforeAvatarUpload"
            :on-success="handleSuccess"
            :on-remove="handleRemove"
            :on-exceed="handleExceed"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>
        </el-form-item>
        <div>
          <el-checkbox v-model="checked">已阅读并同意</el-checkbox>
          <span class="agreement" @click="getAgreement">《入驻协议》</span>
        </div>
        <div style="text-align: center;margin-top:20px;">
          <el-button type="primary" @click="onSubmit">提交申请</el-button>
        </div>
      </el-form>
    </div>
    <!--入驻协议-->
    <div v-if="showProtocal" class="protocolModal" @click.stop="showProtocal=false">
      <div class="protocolCount">
        <div class="protocolMain">
          <div class="title">{{title}}</div>
          <div class="content">
            <div class="content-main" v-html="agreement"></div>
          </div>
          <div class="sureBbtn" v-if="isSettled">
            <el-button type="primary" @click="showProtocal=false;checked=true;">同意并继续</el-button>
          </div>
          <div class="sureBbtn" v-else>
            <el-button type="primary" @click="showProtocal=false;">我知道了</el-button>
          </div>
        </div>

      </div>
    </div>
    <Verify @success="verifySuccess" captchaType="blockPuzzle" :imgSize="{ width: '330px', height: '155px' }" ref="verify"></Verify>
  </div>
</template>
<script>
// +----------------------------------------------------------------------
// | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2021 https://www.crmeb.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
// +----------------------------------------------------------------------
// | Author: CRMEB Team <admin@crmeb.com>
// +----------------------------------------------------------------------
import {Message} from 'element-ui';
import sendVerifyCode from "@/mixins/SendVerifyCode";
import Verify from '@/components/verifition/Verify';
export default {
  name: "merchantSettled",
  auth: "guest",
  components: {Verify},
  mixins: [sendVerifyCode],
  data() {
    var checkphone = (rule, value, callback) => {
      // let phoneReg = /(^1[3|4|5|6|7|8|9]\d{9}$)|(^09\d{8}$)/;
      if (value == "") {
        callback(new Error("请输入手机号"));
      } else if (!this.isCellPhone(value)) {//引入methods中封装的检查手机格式的方法
        callback(new Error("请输入正确的手机号!"));
      } else {
        callback();
      }
    };
    return {
      upLoadUrl: process.env.BASE_URL + "/api/upload/image/file",
      imgUrl: [],
      pics: [],
      tables: {
        /*表格数据*/
        tableData: [],
        /*默认显示页码*/
        currentPage: 1,
        /*总数*/
        total: 0,
        /*当前页*/
        page: 1,
        /*分页*/
        limit: 10,
        /*加载框*/
        tableLoading: false
      },
      ruleForm: {
        name: '',
        username: '',
        phone: '',
        yanzhengma: '',
        classification: '',
        type: '',
        images: []
      },
      dialogImageUrl: '',
      dialogVisible: false,
      hideUpload: false,
      checked: false,
      showProtocal: false,
      isShowCode: false,
      codeVal: '',
      codeUrl: '',
      keyCode: '',
      codeKey: '',
      validate: false,
      array: [],
      typeArray: [],
      intention_id: '',
      title: '入驻协议',
      agreement: '',
      isSettled: false,
      rules: {
        name: [
          {required: true, message: '请输入商户名称', trigger: 'blur'},
          {min: 3, max: 15, message: '长度在 3 到 15 个字符', trigger: 'blur'}
        ],
        username: [
          {required: true, message: '请输入用户姓名', trigger: 'blur'},
          {min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur'}
        ],
        yanzhengma: [
          {required: true, message: '请输入验证码', trigger: 'blur'}
        ],
        phone: [
          {required: true, message: '请输入手机号', validator: checkphone, trigger: 'blur'}
        ],
        classification: [
          {required: true, message: '请选择商户分类', trigger: 'change'}
        ],
        type: [
          {required: true, message: '请选择店铺类型', trigger: 'change'}
        ]
      },
      uploadLimit: 10,
      currentLimit: 10
    };
  },
  fetch({store}) {
    store.commit("isBanner", false);
    store.commit("isHeader", true);
    store.commit("isFooter", true);
  },
  head() {
    return {
      title: "入驻申请-" + this.$store.state.titleCon
    }
  },
  beforeMount() {
    if(!this.$auth.loggedIn){
      this.$store.commit("isLogin", true);
    }
    this.intention_id = this.$route.query.intention_id;
    this.getClassfication();
    this.getTypeArray();
    // this.getAgreement();
    if (this.intention_id) this.getDetails(this.intention_id)
  },
  mounted() {
  },
  methods: {
    //检查手机号
    isCellPhone(val) {
      if (!/^1(3|4|5|6|7|8)\d{9}$/.test(val)) {
        return false;
      } else {
        return true;
      }
    },
    //编辑时候进来获取历史提交数据
    getDetails(id) {
      let that = this;
      that.$axios.get("/api/intention/detail/" + id).then(res => {
        let data = res.data;
        this.ruleForm = {
          name: data.mer_name,
          username: data.name,
          phone: data.phone,
          yanzhengma: '',
          classification: data.merchant_category_id,
          type: data.mer_type_id,
        };
        this.imgUrl = data.images
        this.currentLimit = this.uploadLimit - this.imgUrl.length || -1;
        // this.pics = data.images
        this.checked = true;
      }).catch(err => {
        that.$message.error(err);
      });
    },
    //获取商户分类
    getClassfication() {
      let that = this;
      that.$axios.get("/api/intention/cate").then(res => {
        that.array = res.data
      }).catch(err => {
        that.$message.error(err);
      });
    },
    //获取店铺类型
    getTypeArray() {
      let that = this;
      that.$axios.get("/api/intention/type").then(res => {
        that.typeArray = res.data
      }).catch(err => {
        that.$message.error(err);
      });
    },
    //获取入驻协议内容
    getAgreement() {
      let that = this;
      that.$axios.get("/api/config").then(res => {
        that.agreement = res.data.sys_intention_agree
        that.title = '入驻协议'
        that.showProtocal = true
        that.isSettled = true;
      }).catch(err => {
        that.$message.error(err);
      });
    },
    //店铺类型协议
    getStoreType() {
      let that = this;
      that.$axios.get("/api/agreement/sys_merchant_type").then(res => {
        that.agreement = res.data.sys_merchant_type
        that.title = '店铺类型说明'
        that.showProtocal = true
        that.isSettled = false
      }).catch(err => {
        that.$message.error(err);
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    again() {
      this.getcaptcha()
    },
    getcaptcha() {
      let that = this;
      that.$axios.get("/api/captcha").then(res => {
        that.codeUrl = data.data.captcha; //图片路径
        that.codeVal = data.data.code; //图片验证码
        that.codeKey = data.data.key //图片验证码key
        that.isShowCode = true;
      }).catch(err => {
        that.$message.error(err);
      });
    },
    async code(data) {
      let that = this;
      if (!that.ruleForm.phone) return that.$message.error('请填写手机号码');
      if (!/^1(3|4|5|7|8|9|6)\d{9}$/i.test(that.ruleForm.phone)) return that.$message.error('请输入正确的手机号码');
      this.$axios.post("/api/auth/verify", {
        phone: that.ruleForm.phone,
        type: 'intention',
        // key: that.keyCode,
        captchaType: "blockPuzzle",
        captchaVerification: data.captchaVerification
      }).then(res => {
        that.$message.success(res.message);
        that.sendCode();
      }).catch(err => {
        that.$message.error(err);
      });
    },
    onSubmit() {
      let that = this;
      if(!this.$auth.loggedIn){
        return Message.warning('请登录');
      }
      if (that.validateForm() && that.validate) {
        let requestData = {
          phone: that.ruleForm.phone,
          mer_name: that.ruleForm.name,
          name: that.ruleForm.username,
          code: that.ruleForm.yanzhengma,
          merchant_category_id: that.ruleForm.classification,
          mer_type_id: that.ruleForm.type,
          images: that.imgUrl.concat(that.pics)
        }
        // if (!requestData.images.length) {
        //   return Message.error('请上传营业执照及行业相关资质证明图片');
        // }
        if (that.intention_id) {
          that.$axios.post("/api/intention/update/" + that.intention_id, requestData).then(res => {

            that.$message.success(res.message);
            that.$router.push({
              path: `/user/settle_record`,
              query: {
                type: 1
              }
            })
          }).catch(err => {
            that.$message.error(err);
          });
        } else {
          that.$axios.post("/api/intention/create", requestData).then(res => {
            that.$message.success(res.message);
            that.$router.push({
              path: `/user/settle_record`,
              query: {
                type: 1
              }
            })
          }).catch(err => {
            that.$message.error(err);
          });
        }
      }
    },
    validateForm: function () {
      let that = this,
        value = that.ruleForm;
      if (!value.name) return Message.error('请输入商户名称');
      if (!value.username) return Message.error('请输入用户姓名');
      if (!value.phone) return Message.error('请输入手机号');
      if (!/^1(3|4|5|7|8|9|6)\d{9}$/i.test(value.phone)) return Message.error('请输入正确的手机号码');
      if (!value.yanzhengma) return Message.error('请填写验证码');
      if (!value.classification) return Message.error('请选择商户分类');
      if (!that.checked) return Message.error('请勾选并同意入驻协议');
      if (that.isShowCode && !that.codeVal) return Message.error('请填写图片验证码');
      that.validate = true;
      return true;
    },
    //上传图片前的图片验证回调
    beforeAvatarUpload(file) {
      //图片格式
      const isJPG = file.type === 'image/jpg' || file.type === 'image/png' || file.type === 'image/jpeg';
      //图片大小
      const isLt2M = file.size / 1024 / 1024 <= 2;
      if (!isJPG) {
        this.$message.error('上传图片只能为jpg/jpeg或png格式');
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过2MB');
      }
      const _this = this;
      return isJPG && isLt2M;
    },
    handleExceed() {
      this.$message.warning("最多上传10张图片");
    },
    handleRemove(file, fileList) {
      this.pics = [];
      fileList.forEach(item => {
        this.pics.push(item.response.data.url);
      });
      this.currentLimit = this.uploadLimit - this.pics.length - this.imgUrl.length || -1;
    },
    handleRemove1(index) {
      this.imgUrl.splice(index, 1)
      this.currentLimit = this.uploadLimit - this.imgUrl.length || -1;
    },
    // 文件上传失败时的钩子
    handleError(err, file, fileList) {
    },
    handleSuccess(response) {
      if (response.status === 200) {
        this.pics.push(response.data.path);
      } else if (response.status === 400) {
        this.$message.error(response.msg);
      }
    },
    getVerify() {
        let that = this;
        if (!that.ruleForm.phone) return that.$message.error('请填写手机号码');
        if (!/^1(3|4|5|7|8|9|6)\d{9}$/i.test(that.ruleForm.phone)) return that.$message.error('请输入正确的手机号码');
        this.$refs.verify.show();
    },
    verifySuccess(params) {
        this.closeModel(params);
    },
    // 关闭模态框
    closeModel(params) {
        this.isShow = false;
        this.code(params);
    },

  }
}
</script>

<style lang="scss" scoped>
.settled-wrapper {
  background: #fff;
  padding: 0 91px 44px 109px;

  .user-com-title {
    font-size: 20px;
    color: #282828;
    text-align: center;
    line-height: 30px;
    border-bottom: 1px solid #EFEFEF;
  }

  .demo-ruleForm {
    margin-top: 30px;

    .el-form-item {
      margin-bottom: 34px;
    }

    .el-input {
      width: 330px;
      height: 36px;
      line-height: 36px;
    }

    .verifiCode {
      width: 200px;

    }

    .code {
      width: 96px;
      height: 36px;
      line-height: 36px;
      text-align: center;
      color: #E93323;
      border: 1px solid #E93323;
      border-radius: 4px;
      margin-left: 14px;
      background: #fff;
    }

    .el-form-item__label, .text {
      color: #666666;
    }

    /deep/ .el-checkbox__input.is-checked + .el-checkbox__label {
      color: #666666;
    }

    .text-desc {
      font-size: 12px;
      color: #999999;
    }
  }
  .el-form-item {
    position: relative;
  }
  .wenhao {
    display: inline-block;
    text-align: center;
    width: 17px;
		height: 17px;
    line-height: 17px;
		font-size: 14px;
		border-radius: 50%;
		background: #E3E3E3;
		color: #ffffff;
		margin-left: 4px;
    cursor: pointer;
  }
  .agreement {
    color: #E93323;
    font-family: 'PingFang SC';
    cursor: pointer;
  }
}

.hide .el-upload--picture-card {
  display: none;
}

.protocolModal {
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, .5);
  position: fixed;
  top: 0;
  left: 0;
  z-index: 999;

  .protocolCount {
    width: 900px;
    height: 800px;
    position: absolute;
    top: 50%;
    left: 50%;
    margin-top: -350px;
    margin-left: -450px;
    .protocolMain {
      width: 100%;
      height: 710px;
      background: #fff;
      border-radius: 6px;
      padding: 0 32px;
      .title {
        padding: 20px 0;
        text-align: center;
        color: #333333;
        font-size: 20px;
        font-weight: bold;
      }

      .content-main {
        color: #333;
        line-height: 20px;
        overflow-y: auto;
        height: 500px;
      }
    }
  }

  .sureBbtn {
    text-align: center;
    margin-top: 60px;

    .el-button {
      width: 180px;
      height: 46px;
      // line-height: 46px;
    }
  }
}
</style>
